import { merge } from 'lodash-es'
import type { App } from 'vue'
import { createI18n, type DefineLocaleMessage } from 'vue-i18n'

export const i18n = createI18n({
  legacy: false,
  globalInjection: true,
  // locale: locale, // 默认语言
  fallbackLocale: 'en', // 回退语言
  silentTranslationWarn: true,
  missingWarn: false,
  silentFallbackWarn: true,
  messages: {},
})

export const $t = i18n.global.t

/**
 * 获取语言包并和本地语言包合并
 * @param lang 语言标识
 * @returns 合并后的语言包
 */
async function getLangRes(lang: string): Promise<DefineLocaleMessage> {
  try {
    const localeLang = await import(`./langs/${lang}/index.ts`)
    // const apiLang = await getLocaleApi(lang)
    // 接口返回语言包
    const apiLang = {}
    return merge(localeLang.default ?? {}, apiLang)
  } catch (error) {
    console.error(`Failed to load language ${lang}:`, error)
    return {}
  }
}

/**
 * 改变语言
 * @param lang 语言标识
 */
export const changeLocale = async (lang: string) => {
  const currentLocale = unref(i18n.global.locale)
  if (currentLocale === lang) {
    return
  }
  if (!i18n.global.availableLocales.includes(lang)) {
    const langs = await getLangRes(lang)
    i18n.global.setLocaleMessage(lang, langs)
  }
  document?.querySelector('html')?.setAttribute('lang', lang)
  i18n.global.locale.value = lang
  await nextTick()
}

export const setupI18n = async (app: App) => {
  const { locale } = useLocaleStoreWithOut()
  await changeLocale(locale)
  app.use(i18n)
}
